package com.example.day1210_section_information.fraction;

import com.example.day1210_section_information.MainAbility;
import com.example.day1210_section_information.NetworkManger;
import com.example.day1210_section_information.Provider.NewsListProvider;
import com.example.day1210_section_information.Provider.NewsTypeList;
import com.example.day1210_section_information.ResourceTable;
import com.example.day1210_section_information.bean.NewsInfo;
import com.example.day1210_section_information.bean.NewsType;
import com.example.day1210_section_information.utils.CommonUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import com.example.day1210_section_information.bean.Data;
import ohos.hiviewdfx.HiLogLabel;

import java.io.IOException;
import java.util.List;

public class NewsListFraction extends Fraction {

    private static final HiLogLabel LABEL_LOG = new HiLogLabel(0, 0, "NewsListFraction.class");

    private ListContainer listContainer;
    private NewsListProvider mNewsListProvider;
    private List<Data> data;
    private Component mComponent;

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        try {
            int color = getResourceManager().getElement(ResourceTable.Color_title_color).getColor();
            getFractionAbility().getWindow().setStatusBarColor(color);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }



        mComponent = scatter.parse(ResourceTable.Layout_fraction_news_list, null, false);

        initTypeCompent();
        initNewsPage();

        return mComponent;
    }


    /**
     * x新闻信息
     */
    private void NewsInfos(String type) {
        NetworkManger networkManger = NetworkManger.getInstance();
        NetworkManger.NetworkCallback networkCallback = new NetworkManger.NetworkCallback() {
            @Override
            public void onSuccess(NewsInfo newsInfo) {
                // 请求成功
                new ToastDialog(getContext()).setText(newsInfo.getReason()).show();

                if (mNewsListProvider != null && newsInfo != null && newsInfo.getResult() != null
                        && newsInfo.getResult().getData() != null) {
                    data = newsInfo.getResult().getData();
                    mNewsListProvider.setData(data);
                }

            }

            @Override
            public void onFail(String result) {
                // 请求失败
                new ToastDialog(getContext()).setText(result).show();
            }
        };

        networkManger.requestNewsInfo(getContext(), type, networkCallback);
    }

    /**
     * 初始化新闻主页
     */
    private void initNewsPage() {

        ListContainer newspageContainer = mComponent.findComponentById(ResourceTable.Id_news_page_listcontainer);

        mNewsListProvider = new NewsListProvider();
        newspageContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Data item = (Data) mNewsListProvider.getItem(i);
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName(MainAbility.class.getName())
                        .withAction("NewsPageInfo")
                        .build();

                intent.setOperation(operation);
                intent.setParam("key_data", item);
                startAbility(intent,0);


            }
        });


        newspageContainer.setItemProvider(mNewsListProvider);
    }


    /**
     * 初始化新闻分类组件
     */
    private void initTypeCompent() {
        String path = "entry/resources/rawfile/news_type_datas.json";

        Gson gson = new Gson();
        String jsonPath = CommonUtils.getStringFromJsonPath(getContext(), path);
        List<NewsType> fromJson = gson.fromJson(jsonPath, new TypeToken<List<NewsType>>() {
        }.getType());


        HiLog.info(LABEL_LOG, jsonPath);
        HiLog.info(LABEL_LOG, String.valueOf(fromJson));

        listContainer = mComponent.findComponentById(ResourceTable.Id_news_type_listcontainer);
        if (fromJson != null && fromJson.size() > 0) {
            HiLog.info(LABEL_LOG, jsonPath);

            NewsType newsType = fromJson.get(0);
            NewsInfos(newsType.getType());

            newsType.setSelect(true);
// 初始化item
            NewsTypeList newsTypeList = new NewsTypeList(fromJson, getContext());

            //  给item监听
            listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
                @Override
                public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                    for (int j = 0; j < fromJson.size(); j++) {
                        NewsType newsType = fromJson.get(j);
                        newsType.setSelect(i == j ? true : false);
                    }


                    NewsType newsType1 = fromJson.get(i);
                    NewsInfos(newsType1.getType());

                    //  通知更新
                    newsTypeList.notifyDataChanged();

                }

            });
            // 让lisetContainer 关联 item 布局
            listContainer.setItemProvider(newsTypeList);
        }

    }


}
